package com.cm.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cm.common.core.Result;
import com.cm.common.utils.COSStorage;
import com.cm.common.utils.StringUtil;
import com.cm.common.entity.User;
import com.cm.user.entity.dto.UserKeyWordDTO;
import com.cm.user.mapper.UserMapper;
import com.cm.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @类 名：UserController </br>
 * @描 述：</br>
 * @日 期：2020/9/19 10:57</br>
 * @作 者：刘海龙</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/user")
public class   UserController {
//    @GetMapping("/getUserName")
//    public String getUserName(String username, HttpServletRequest request) {
//        String str="本地端口"+request.getLocalPort()+"远程端口："+request.getRemotePort()+"服务端口："+request.getServerPort();
//        return "用户名为:" + username+str;
//    }
//
//    @GetMapping("/getUserData")
//    public User getUserData(@RequestParam String username) {
//        User user=new User();
//        user.setUsername(username);
//        user.setPassword("991216");
//        user.setId(520L);
//        return user;
//    }
//
//    @PostMapping("/getUpdateUser")
//    public User getUpdateUser(@RequestBody User user) {
//        return user;
//    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @PostMapping("/insert")
    public Result insert(@RequestBody User user){
        if(userService.insert(user)){
            return Result.success("用户添加成功");
        }
        return Result.fail(user.getAccount()+"已存在！");
    }
    @PostMapping("/delete")
    public Result delete(Long id){
        if (userService.delete(id)){
            return  Result.success("删除成功");
        }
        return  Result.fail("删除失败");
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        if(userService.update(user)){
            return Result.success("修改成功");
        }
        return  Result.fail("修改失败");
    }
    @PostMapping("/list")
    public Result getUsers(@RequestBody UserKeyWordDTO userKeyWordDTO) {
        IPage<User> userIPage = userService.getUserList(userKeyWordDTO);
        return Result.success(userIPage);
    }
    @PostMapping("/getById")
    public Result getById(Long id){
        User user=userService.select(id);
        return Result.success(user);
    }
    @PostMapping("/setPhoto")
    public Result upload(MultipartFile file) throws IOException {
        String filename=file.getOriginalFilename();
        InputStream inputStream=file.getInputStream();
        COSStorage cosStorage = new COSStorage();
        String path = cosStorage.upload(inputStream, StringUtil.getFileExt(filename));
        return Result.success(path);
    }
}
